package studentinformationmanagementsystem.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置返回的编码，防止乱码
        request.setCharacterEncoding("utf-8");  //请求编码
        response.setCharacterEncoding("utf-8"); //响应编码

        //设置页面编码格式防止乱码
        response.setContentType("text/html;charset=utf-8");  //服务器返回给前端的编码，防止返回是中文的错误
        //根据 action 的值决定调用哪个方法的逻辑
        //1.获取action的值
        String action=request.getParameter("action");
        //2.使用反射获取当前的类的方法
        try {
         Method method=this.getClass().getMethod(action,HttpServletRequest.class,HttpServletResponse.class);
            //为了防止方法的权限为private、或者其他的私有权限，使用无视权限调用
            method.setAccessible(true);

            //通过反射调用方法
            method.invoke(this,request,response);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置返回的编码，防止乱码
        request.setCharacterEncoding("utf-8");  //请求编码
        response.setCharacterEncoding("utf-8"); //响应编码

        //设置页面编码格式防止乱码
        response.setContentType("text/html;charset=utf-8");  //服务器返回给前端的编码，防止返回是中文的错误
        doGet(request, response);
    }
}
